import React, { Component } from 'react';
import { connect } from 'dva';
import { Button, Card, Col, Form, Input, message, Modal, Radio, Row, Table, Select, DatePicker, Spin, Tooltip, Popconfirm, Cascader } from 'antd';
import {PageHeaderWrapper} from "@ant-design/pro-layout";
import { FormattedMessage } from 'umi/locale';
import APP from '@/components/Tool/BaseAPP';
import ChinaArea from '@/components/Tool/ChinaArea';
import moment from "moment";

/**
 * 分页参数
 * @Author 肖家添
 * @Date 2019/8/22 15:09
 */
let pagingData = {
  _pageSize: 10,
  _current: 1,
  _total: 0,
};

@connect(({ systemUserModel, loading, userModel }) => ({  // 连接usermanage.js文件
  systemUserModel,
  loading: loading.models.user_manage,
    userModel
}))
@Form.create()
class UserManage extends Component {

  state = {
    loading: false,
    isShowEditModal: false,
    selectedKeys: [],
    editData: {},
    pageDataSource: [],
      isShowEditPwdModal: false,
      editPwdUserId: null
  };

  componentDidMount() {
    this.findPageDataSource();
  }

  findPageDataSource = (e) => {
    let that = this, params = {...pagingData};
    if(e){
      pagingData._current = 1;
      e.preventDefault();
    }
    const { form } = this.props;
    form.validateFieldsAndScroll((err, values) => {
      APP.validNilParams(values);
      params = {...params, ...values};
      requestContinue();
    });
    function requestContinue(){
      const { dispatch } = that.props;
      APP.loading(that);
      dispatch({
        type: "systemUserModel/fetch",
        payload: params,
        callback: function(data){
          APP.closeLoading(that);
          if(data.success){
            const { list, pagination } = data.datas;
            pagingData._current = pagination.current;
            pagingData._pageSize = pagination.pageSize;
            pagingData._total = pagination.total;
            that.setState({
              pageDataSource: list,
              selectedKeys: []
            });
          }
        }
      });
    }
  };

  getById = () => {
    const { selectedKeys } = this.state;
    if(selectedKeys.length !== 1) return;
    const that = this,
      { dispatch } = that.props,
      id = selectedKeys[0];
    if(!APP.isValidObj(id)) return;
    APP.loading(that);
    dispatch({
      type: "systemUserModel/fetchById",
      payload: {id: id},
      callback: function(data){
        that.setState({
          loading: false,
          editData: data.datas,
          isShowEditModal: true
        });
      }
    });
  };

    enabledControl = (isEnabled) => {
    const { selectedKeys } = this.state;
    if(selectedKeys.length === 0) return;
    const that = this,
      { dispatch } = that.props;
    const ids = selectedKeys.toLocaleString();
    APP.loading(that);
    dispatch({
      type: "systemUserModel/enabledControl",
      payload: {
          ids: ids,
          isEnabled: isEnabled
      },
      callback: function(data){
        that.findPageDataSource();
      }
    });
  };

  exportData = (type) => {
      APP.exportData({
          parent: this,
          requestUrl: "/api/employee/exportData",
          fileNamePrefix: "员工",
          exportType: type,
          tablePagination: pagingData
      });
  };

  render() {
    const that = this;
    const { loading, selectedKeys, pageDataSource } = that.state;
    const { form } = that.props;
    const { getFieldDecorator } = form;
    return (
      <Spin spinning={loading}>
        <PageHeaderWrapper title={<FormattedMessage id="menu.settings.systemUser"/>}>
          <Card style={{marginBottom: 15}}>
            <Form layout="inline" onSubmit={this.findPageDataSource}>
              <Row>
                <Col span={8}>
                  <Form.Item label="员工姓名">
                    {getFieldDecorator('name', {})(<Input placeholder="请输入员工姓名"/>)}
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label="手机号/账号">
                    {getFieldDecorator('phone', {})(<Input placeholder="请输入手机号/账号"/>)}
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label="员工类型">
                    {getFieldDecorator('postId', {})(<Select placeholder={"请选择员工类型"} allowClear={true} style={{ width: 174}}>
                      <Select.Option key={1} value={1}>安装师傅</Select.Option>
                      <Select.Option key={2} value={2}>销售员</Select.Option>
                      <Select.Option key={4} value={4}>财务</Select.Option>
                      <Select.Option key={3} value={3}>总经理</Select.Option>
                      <Select.Option key={5} value={5}>系统管理员</Select.Option>
                      <Select.Option key={6} value={6}>其他</Select.Option>
                    </Select>)}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col style={{ textAlign: 'center', height: '32px', lineHeight: '32px', marginTop: 20 }}>
                  <Button type="primary" htmlType="submit" {...APP.buttonsStyle_MR15}>
                    查找
                  </Button>
                  <Button type="primary" {...APP.buttonsStyle_MR15} onClick={() => this.exportData(1)}>
                    导出本页
                  </Button>
                  <Button type="primary" {...APP.buttonsStyle_MR15} onClick={() => this.exportData(2)}>
                    导出所有
                  </Button>
                </Col>
              </Row>
            </Form>
          </Card>
          <Card style={{marginBottom: 15}}>
            <Button type="primary" {...APP.buttonsStyle_MR15} onClick={() => {
              this.setState({isShowEditModal: true});
            }}>
              新增
            </Button>
            <Tooltip
              title={selectedKeys.length === 1 ? '' : '请选中一行数据'}
            >
              <Button type="primary" {...APP.buttonsStyle_MR15} onClick={() => this.getById()}>
                编辑
              </Button>
            </Tooltip>
              <Tooltip title={selectedKeys.length > 0 ? '' : '请选中数据'}>
                  <Popconfirm
                      title="确定激活选中数据吗？"
                      onConfirm={() => this.enabledControl(1)}
                      okText="激活"
                      cancelText="取消"
                      disabled={!(selectedKeys.length > 0)}
                  >
                      <Button type="primary" {...APP.buttonsStyle_MR15}>
                          激活
                      </Button>
                  </Popconfirm>
              </Tooltip>
              <Tooltip title={selectedKeys.length > 0 ? '' : '请选中数据'}>
                  <Popconfirm
                      title="确定冻结选中数据吗？"
                      onConfirm={() => this.enabledControl(0)}
                      okText="冻结"
                      cancelText="取消"
                      disabled={!(selectedKeys.length > 0)}
                  >
                      <Button type="primary" {...APP.buttonsStyle_MR15}>
                          冻结
                      </Button>
                  </Popconfirm>
              </Tooltip>
            <Tooltip title={selectedKeys.length > 0 ? '' : '请选中数据'}>
              <Popconfirm
                title="确定删除选中数据吗？"
                onConfirm={() => this.enabledControl(-1)}
                okText="删除"
                cancelText="取消"
                disabled={!(selectedKeys.length > 0)}
              >
                <Button type="primary" {...APP.buttonsStyle_MR15}>
                  删除
                </Button>
              </Popconfirm>
            </Tooltip>
              <Tooltip title={selectedKeys.length === 1 ? '' : '请选中一行数据'}>
                  <Button type="primary" {...APP.buttonsStyle_MR15} onClick={() => this.handlerResetAccountPassword()}>
                      重置员工密码
                  </Button>
              </Tooltip>
          </Card>
          <Card>
            <Table
              bordered
              rowKey={data => `${data.id}`}
              rowSelection={APP.tableRowSelection(function(selectedRowKeys, selectedRows){
                that.setState({ selectedKeys: selectedRowKeys });
              }, selectedKeys)}
              columns={this.columns}
              dataSource={pageDataSource}
              pagination={{
                pageSize: pagingData._pageSize,
                current: pagingData._current,
                total: pagingData._total,
                onChange: (page, pageSize) => {
                  pagingData._current = page;
                  this.findPageDataSource();
                },
                  showTotal: total => `共 ${total} 条数据`,
              }}
            />
          </Card>
          <EditForm parent={this}/>
            <EditPwdForm parent={this}/>
        </PageHeaderWrapper>
      </Spin>
    )
  }

  columns = [{
    title: '员工姓名',
    dataIndex: 'name',
    key: 'name',
  },{
    title: '性别',
    dataIndex: 'sex',
    key: 'sex',
  },{
    title: '手机号/账号',
    dataIndex: 'phone',
    key: 'phone',
  },{
    title: '员工类型',
    dataIndex: 'postName',
    key: 'postName',
  },{
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
  },{
      title: '运营商',
      dataIndex: 'oname',
      key: 'oname',
  },{
      title: '账号状态',
      dataIndex: 'isenabled',
      key: 'isenabled',
  },{
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
  }];

    handlerResetAccountPassword = () => {
        const { selectedKeys, pageDataSource } = this.state;
        if(selectedKeys.length !== 1) return;
        let userId = null;
        pageDataSource.forEach((item) => {
            if(item.id === parseInt(selectedKeys[0])){
                userId = item.userId;
            }
        });
        if(!APP.isValidObj(userId)) return;
        this.setState({
            isShowEditPwdModal:true,
            editPwdUserId:userId
        });
    };
}

const EditForm = Form.create()(props => {
  let { parent,form } = props;
  const { dispatch } = parent.props;
  const { loading, isShowEditModal, editData } = parent.state;
  const formItemLayout = {
    style: {
      margin: '0px',
    },
  };
  const { getFieldDecorator } = form;
  //-- 显示/隐藏 数据编辑窗口
  function handlerEditModal(){
    form.resetFields();
    let { isShowEditModal, editData } = parent.state;
    isShowEditModal = !isShowEditModal;
    editData = {};
    parent.setState({ isShowEditModal, editData });
  }
  //-- 提交
  function submit(){
    form.validateFields((err, values) => {
      if(err) return;
      APP.validNilParams(values);
      request(values);
    });
    function request(params){
      APP.loading(parent);
      dispatch({
        "type": "systemUserModel/add",
        payload: params,
        callback: function(data){
          APP.closeLoading(parent);
          if(data.success){
            parent.findPageDataSource();
            handlerEditModal();
            if (data.datas.password) {
                let postId = params.postId;
                switch (postId) {
                    case 1:
                        postId = '安装师傅';
                        break;
                    case 2:
                        postId = '销售员';
                        break;
                    case 3:
                        postId = '总经理';
                        break;
                    case 4:
                        postId = '财务';
                        break;
                    case 5:
                        postId = '系统管理员';
                        break;
                    default:
                        postId = '其他';
                        break;
                }
                Modal.success({
                    title: '保存成功',
                    content: postId + '的账号为：' + params.phone + '，登录密码为：' + data.datas.password + '。',
                });
            } else {
                message.success("保存成功！");
            }
          }else{
            message.error(data.msg);
          }
        }
      });
    }
  }
  //-- 地区默认选中地址
  const areaDefaultValues = new Array();
  let userId = null;
  if(editData.id){
    const { provinceId, cityId, regionId } = editData;
    for (const id of [provinceId, cityId, regionId]) {
      if(APP.isValidObj(id)){
        areaDefaultValues.push(id.toString());
      }
    }
    const { selectedKeys, pageDataSource } = parent.state;
    pageDataSource.forEach((item) => {
      if(item.id == selectedKeys[0]){
        userId = item.userId;
      }
    });
  }
  return (
    <Modal
      title="编辑员工"
      visible={isShowEditModal}
      onOk={() => submit()}
      onCancel={() => handlerEditModal()}
      okText="保存"
      confirmLoading={loading}
    >
      <Form layout="vertical">
        {getFieldDecorator('id', {initialValue: editData.id})(<Input type="hidden" readOnly/>)}
        {getFieldDecorator('userId', {initialValue: userId})(<Input type="hidden" readOnly/>)}
        <Row>
          <Col span={11}>
            <Form.Item label="员工姓名" {...formItemLayout}>
              {getFieldDecorator('name', {
                initialValue: editData.name,
                rules: [
                  {
                    required: true,
                    message: '请输入员工姓名！',
                  },
                ],
              })(<Input placeholder="请输入员工姓名" />)}
            </Form.Item>
          </Col>
          <Col span={11} style={{ float: 'right' }}>
            <Form.Item label="性别" {...formItemLayout}>
              {
                getFieldDecorator('sex', {
                  initialValue: editData.hasOwnProperty("id") ? editData.sex : 1,
                  rules: [
                    {
                      required: true,
                      message: '请选择性别！',
                    },
                  ],
                })(
                  <Radio.Group>
                    <Radio value={1}>男士</Radio>
                    <Radio value={2}>女士</Radio>
                  </Radio.Group>
                )
              }
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={11}>
            <Form.Item label="手机/账号" {...formItemLayout}>
              {getFieldDecorator('phone', {
                initialValue: editData.phone,
                rules: [
                  {
                    required: true,
                    message: '请输入手机号/账号！',
                  },
                  {
                    pattern: /^1\d{10}$/,
                    message: '手机号/账号格式错误！'
                  },
                ],
              })(<Input placeholder="请输入手机号/账号" readOnly={editData.phone} />)}
            </Form.Item>
          </Col>
          <Col span={11} style={{ float: 'right' }}>
            <Form.Item label="员工类型" {...formItemLayout}>
              {getFieldDecorator('postId', {
                initialValue: editData.postId,
                rules: [
                  {
                    required: true,
                    message: '请选择员工类型！',
                  }
                ],
              })(
                <Select placeholder="请选择员工类型" allowClear={true}>
                  <Select.Option key={1} value={1}>安装师傅</Select.Option>
                  <Select.Option key={2} value={2}>销售员</Select.Option>
                  <Select.Option key={4} value={4}>财务</Select.Option>
                  <Select.Option key={3} value={3}>总经理</Select.Option>
                  <Select.Option key={5} value={5}>系统管理员</Select.Option>
                  <Select.Option key={6} value={6}>其他</Select.Option>
                </Select>
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={11}>
            <Form.Item label="邮箱" {...formItemLayout}>
              {getFieldDecorator('email', {
                initialValue: editData.email,
                rules: [
                    {
                        required: true,
                        message: '请输入邮箱！',
                    },
                    {
                        pattern: /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/,
                        message: '邮箱格式错误！'
                    },
                ],
              })(<Input placeholder="请输入邮箱" allowClear={true} />)}
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col>
            <Form.Item label="备注" {...formItemLayout}>
              {
                getFieldDecorator('remark', {
                  initialValue: editData.remark,
                })(<Input.TextArea
                  placeholder="请输入备注"
                  className="custom"
                  style={{ height: 150 }}
                />)
              }
            </Form.Item>
          </Col>
        </Row>
      </Form>

    </Modal>
  );
});

const EditPwdForm = Form.create()(props => {
    let {parent, form} = props;
    const {dispatch} = parent.props;
    const {loading, isShowEditPwdModal, editPwdUserId} = parent.state;
    const {getFieldDecorator} = form;
    const formItemLayout = {
        style: {
            margin: '0px',
        },
    };

    //-- 显示/隐藏 数据编辑窗口
    function handlerEditModal() {
        form.resetFields();
        let {isShowEditPwdModal} = parent.state;
        isShowEditPwdModal = !isShowEditPwdModal;
        parent.setState({isShowEditPwdModal});
    }

    function submit() {
        form.validateFields((err, values) => {
            if (err) return;
            APP.validNilParams(values);
            if (!/^[A-Za-z\d]{8,20}$/.test(values.passWord)) {
                Modal.error({content:'请输入8-20个字符的新密码'});
                return;
            }
            if (values.passWord !== values.passWordAgain) {
                Modal.error({content:'两次输入密码必须相同'});
                return;
            }
            parent.setState({loading: true});
            dispatch({
                type: 'userModel/editpwd2',
                payload: values,
                callback: function (data) {
                    parent.setState({loading: false});
                    if (data.success) {
                        Modal.info({content:'重置密码成功。'});
                        handlerEditModal();
                    } else {
                        Modal.error({content:data.msg});
                    }
                }
            });
        });
    }

    return(
        <Modal
            title={'重置密码'}
            visible={isShowEditPwdModal}
            onOk={() => submit()}
            onCancel={() => handlerEditModal()}
            okText="确认"
            cancelText='返回'
            confirmLoading={loading}
        >
            <Form layout="vertical">
                {getFieldDecorator('userId', {initialValue: editPwdUserId})(<Input hidden={true}/>)}
                <Row>
                    <Form.Item {...formItemLayout}>
                        {getFieldDecorator('passWord', {
                            initialValue: '',
                            rules: [
                                {
                                    required: true,
                                    message: '请输入新密码',
                                },
                            ],
                        })(<Input placeholder={"请输入新密码"} allowClear={true} type={'password'}/>)}
                    </Form.Item>
                </Row>
                <Row>
                    <Form.Item {...formItemLayout}>
                        {getFieldDecorator('passWordAgain', {
                            initialValue: '',
                            rules: [
                                {
                                    required: true,
                                    message: '请再次输入新密码',
                                },
                            ],
                        })(<Input placeholder={"请再次输入新密码"} allowClear={true} type={'password'}/>)}
                    </Form.Item>
                </Row>
            </Form>
        </Modal>
    );
});

export default UserManage;
